import React, { useEffect, useState } from 'react';
import { Table, Button, Space, Modal, Form, Input, message } from 'antd';
import { getRolesListFromApi, rolesStore } from '@/store/roles/roleStore';
import { getRoleById,deleteRole } from '@/api';
import { useNavigate } from 'react-router-dom';

const Roles = () => {
    const [viewModalVisible, setViewModalVisible] = useState(false);
    const [roleDetail, setRoleDetail] = useState(null);
    const rolesData = rolesStore.getState().rolesList;
    const navigate = useNavigate();

    // 查看角色详情
    const handleView = async (role) => {
        try {
            const data = await getRoleById(role._id);
            setRoleDetail(data);
            setViewModalVisible(true);  
        } catch (error) {
            message.error('获取角色详情失败');
        }
    };

    // 删除角色
    const handleDelete = (role) => {
        Modal.confirm({
            title: '确认删除',
            content: `确定要删除角色 "${role.name}" 吗？`,
            okText: '确认',
            okButtonProps: { danger: true },
            cancelText: '取消',
            onOk: async () => {
                try {
                    await deleteRole(role._id);
                    message.success('删除成功');
                    getRolesListFromApi(); // 刷新列表
                } catch (error) {
                    message.error('删除失败');
                }
            },
        });
    };

    // 表格列配置
    const columns = [
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
            width: '60%',
        },
        {
            title: '操作',
            key: 'action',
            width: '40%',
            render: (_, record) => (
                <Space>
                    <Button 
                        type="link" 
                        style={{ padding: 0 }}
                        onClick={() => handleView(record)}
                    >
                        查看
                    </Button>
                    <Button 
                        type="link" 
                        style={{ padding: 0}}
                        onClick={() => handleDelete(record)}
                    >
                        删除
                    </Button>
                    <Button 
                        type="link" 
                        style={{ padding: 0 }}
                        onClick={() => navigate(`/acl/roles/${record._id}`)}
                    >
                        分配权限
                    </Button>
                </Space>
            ),
        },
    ];

    useEffect(() => {
        getRolesListFromApi();
    }, []);

    return (
        <div className="roles-container">
            <Table
                columns={columns}
                dataSource={rolesData}
                rowKey="_id"
                pagination={false}
                style={{ background: '#fff' }}
            />

            {/* 查看角色详情模态框 */}
            <Modal
                title="查看角色"
                open={viewModalVisible}
                onCancel={() => setViewModalVisible(false)}
                footer={[
                    <Button 
                        key="close" 
                        onClick={() => setViewModalVisible(false)}
                    >
                        关闭
                    </Button>
                ]}
            >
                {roleDetail && (
                    <div>
                        <p><strong>角色名称：</strong>{roleDetail.name}</p>
                        <p><strong>创建时间：</strong>{roleDetail.createdAt}</p>
                        <p><strong>更新时间：</strong>{roleDetail.updatedAt}</p>
                        <p><strong>权限：</strong>{roleDetail.permissions.map(permission => permission.name).join(', ')}</p>
                    </div>
                )}
            </Modal>
        </div>
    );
};

export default Roles;